<?php

namespace XWAM\Model;

/**
 * AdvertisingModel类
 *
 * @since 1.0 <2015-10-23> SoChishun <14507247@qq.com> Added.
 */
class AdvertisingModel extends AppbaseModel {

    protected $tableName = 't_porg_advertising';

    function save_advert() {
        $rules = array(
            array('location', 'require', '位置无效!', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
            array('channel', 'require', '频道无效!', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
            array('name', 'require', '名称无效!', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
            array('title', 'require', '标题无效!', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
            array('code', 'require', '英文名称无效!', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
            array('code', 'require', '英文名称已被使用!', self::MUST_VALIDATE, 'unique', self::MODEL_INSERT),
            array('count', 'number', '数量无效!', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
            array('image_width', 'number', '宽度无效!', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
            array('image_height', 'number', '高度无效!', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
            array('file_type', 'require', '文件格式无效!', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
            array('file_size', 'number', '文件大小无效!', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
            array('status', 'number', '状态无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('user_name', 'require', '用户无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
            array('site_id', 'number', 'SiteID无效!', self::EXISTS_VALIDATE, 'regex', self::MODEL_BOTH),
        );

        if (!$this->validate($rules)->create()) {
            return $this->returnMsg(false, $this->getError());
        }
        if (empty($this->id)) {
            unset($this->data['id']);
            $result = $this->add();
        } else {
            $result = $this->save();
        }
        return $this->returnMsg($result);
    }

    function copy_advert($id) {
        $table = $this->tableName;
        $this->execute("insert into $table (location,channel,name,title,code,count,image_width,image_height,file_type,file_size,status,user_name,site_id) select location,channel,name,concat(title,'_new'),concat(code,'_new'),count,image_width,image_height,file_type,file_size,status,user_name,site_id from $table where id=$id");
        return true;
    }

    function delete_advert($id = '') {
        $undel_ids = $this->table('t_porg_advertising_content')->where(array('advertising_id' => array('in', $id)))->distinct(true)->getField('advertising_id', true);
        if ($undel_ids) {
            $ids = explode(',', $id);
            $id = array_diff($ids, $undel_ids);
        }
        if ($id) {
            $result = $this->delete($id);
            return $this->returnMsg($result);
        } else {
            return $this->returnMsg(false, '没有需要删除的记录');
        }
    }

}
